// 模拟数据开关（开发完成后注释掉下面这行）
const USE_MOCK_API = true;

// 模拟数据生成器
function generateMockData(endpoint) {
  const mockData = {
    USER_INFO: {
      name: '测试用户',
      team: '测试团队',
      avatar: 'assets/images/logo.png'
    },
    SALES_DATA: {
      currentMonthSales: Math.floor(Math.random() * 100000),
      totalSales: Math.floor(Math.random() * 1000000)
    },
    CUSTOMER_COUNT: {
      count: Math.floor(Math.random() * 100)
    },
    ORDER_DETAILS: {
      totalOrders: Math.floor(Math.random() * 1000),
      details: Array.from({ length: 5 }, (_, i) => ({
        orderId: `ORDER_${Date.now()}_${i}`,
        amount: Math.floor(Math.random() * 10000),
        date: new Date().toISOString()
      }))
    }
  };
  return new Promise(resolve => {
    setTimeout(() => resolve(mockData[endpoint]), 500); // 模拟网络延迟
  });
}

// API基础配置
const API_BASE_URL = USE_MOCK_API ? '' : 'https://api.example.com'; // 后端API基础地址
const API_ENDPOINTS = {
  /**
   * 用户信息接口
   * 请求方法：GET
   * 响应格式：
   * {
   *   name: string, // 用户名
   *   team: string, // 团队名称
   *   avatar: string // 头像URL
   * }
   */
  USER_INFO: '/user/info',

  /**
   * 销售数据接口
   * 请求方法：GET
   * 响应格式：
   * {
   *   currentMonthSales: number, // 本月销售额
   *   totalSales: number // 累计销售额
   * }
   */
  SALES_DATA: '/sales/data',

  /**
   * 客户数量接口
   * 请求方法：GET
   * 响应格式：
   * {
   *   count: number // 客户总数
   * }
   */
  CUSTOMER_COUNT: '/customers/count',

  /**
   * 订单详情接口
   * 请求方法：GET
   * 响应格式：
   * {
   *   totalOrders: number, // 总订单数
   *   details: Array<{
   *     orderId: string, // 订单ID
   *     amount: number, // 订单金额
   *     date: string // 订单日期
   *   }>
   * }
   */
  ORDER_DETAILS: '/orders/details'
};

// 通用请求方法
async function apiRequest(endpoint, method = 'GET', data = null) {
  try {
    // 使用模拟数据
    if (USE_MOCK_API) {
      return await generateMockData(endpoint);
    }

    // 真实API请求
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    };

    const response = await fetch(`${API_BASE_URL}${endpoint}`, {
      method,
      headers,
      body: data ? JSON.stringify(data) : null
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
}

// 分销中心页面类
class DistributionCenter {
  constructor() {
    this.user = {
      name: '分销员',
      team: '团队名称',
      avatar: 'assets/images/logo.png',
      sales: 0,
      customers: 0,
      totalSales: 0,
      totalOrders: 0
    };
    this.isLoading = false;
  }

  // 获取用户信息
  async fetchUserInfo() {
    try {
      this.isLoading = true;
      const data = await apiRequest(API_ENDPOINTS.USER_INFO);
      this.user = {
        ...this.user,
        name: data.name || '分销员',
        team: data.team || '团队名称',
        avatar: data.avatar || 'assets/images/logo.png'
      };
    } catch (error) {
      console.error('获取用户信息失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 获取销售数据
  async fetchSalesData() {
    try {
      this.isLoading = true;
      const data = await apiRequest(API_ENDPOINTS.SALES_DATA);
      this.user.sales = data.currentMonthSales || 0;
      this.user.totalSales = data.totalSales || 0;
    } catch (error) {
      console.error('获取销售数据失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 获取客户数量
  async fetchCustomerCount() {
    try {
      this.isLoading = true;
      const data = await apiRequest(API_ENDPOINTS.CUSTOMER_COUNT);
      this.user.customers = data.count || 0;
    } catch (error) {
      console.error('获取客户数量失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 获取订单详情
  async fetchOrderDetails() {
    try {
      this.isLoading = true;
      const data = await apiRequest(API_ENDPOINTS.ORDER_DETAILS);
      this.user.totalOrders = data.totalOrders || 0;
    } catch (error) {
      console.error('获取订单详情失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 更新UI显示
  updateUI() {
    document.querySelector('.username').textContent = this.user.name;
    document.querySelector('.team-name').textContent = this.user.team;
    document.querySelector('.user-avatar img').src = this.user.avatar;
    document.querySelector('.amount').textContent = `¥${this.user.sales.toLocaleString()}`;
    
    document.querySelectorAll('.stat-item')[0].querySelector('.stat-value').textContent = this.user.customers;
    document.querySelectorAll('.stat-item')[1].querySelector('.stat-value').textContent = `¥${this.user.totalSales.toLocaleString()}`;
    document.querySelectorAll('.stat-item')[2].querySelector('.stat-value').textContent = this.user.totalOrders;
  }

  // 绑定事件
  bindEvents() {
    document.querySelectorAll('.detail-btn').forEach(btn => {
      btn.addEventListener('click', async () => {
        try {
          const details = await apiRequest(API_ENDPOINTS.ORDER_DETAILS);
          alert(`订单详情：\n${JSON.stringify(details, null, 2)}`);
        } catch (error) {
          alert('获取订单详情失败');
        }
      });
    });
  }

  // 初始化
  async init() {
    try {
      await Promise.all([
        this.fetchUserInfo(),
        this.fetchSalesData(),
        this.fetchCustomerCount(),
        this.fetchOrderDetails()
      ]);
      this.updateUI();
      this.bindEvents();
    } catch (error) {
      console.error('初始化失败:', error);
    }
  }
}

// 页面加载完成后初始化
window.addEventListener('load', () => {
  const distributionCenter = new DistributionCenter();
  distributionCenter.init();
});
